package micro86.engine;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * (c) Kate Luzhevskaya 2013
 */
public class Utils {
    public static String[] getWordArray(String line){
        List<String> list = new ArrayList<String>();
        Matcher m = Pattern.compile("([^\"\'\\s]\\S*|\".+?\"|\'.+?\'|\"\\S*|\'\\S*)\\s*").matcher(line);
        while (m.find()) {
            list.add(m.group(1));
        }
        String[] array = list.toArray(new String[list.size()]);
        return array;
    }

    public static boolean isNumeric(String str){
       // return str.matches("-?\\d+");
        try {
            Integer.parseInt(str);
        } catch(NumberFormatException e) {
            return false;
        }
        return true;
    }

    public static boolean isMemoryAddress(String str){
        return str.matches("\\[d + \\]");
    }

    public static boolean isRegister(String word) {
        return word.equals("AX") || word.equals("BX") || word.equals("CX");
    }

    public static boolean isQuotedString(String str) {
        return str.length() > 1 && ((str.charAt(0) ==  '\'' &&  (str.charAt(str.length() - 1)) == '\'') || (str.charAt(0) == '\"' &&  (str.charAt(str.length() - 1)) == '\"'));
    }

    public static boolean isLabel(String str) {
        return str.matches(":\\S+");
    }

    public static byte intToByte(int value) {
        return (byte) (value%256);
    }

    public static byte addByte(byte a, byte b) {
        int sum = a + b;
        return Utils.intToByte(sum);
    }

    public static byte subByte(byte a, byte b) {
        int dif = a - b;
        return Utils.intToByte(dif);
    }

    public static byte mulByte(byte a, byte b) {
        int mul = a * b;
        return Utils.intToByte(mul);
    }


    public static byte[] divByte(byte a, byte b) {
        byte[] result = new byte[2];
        result[0] = Utils.intToByte(a/b);
        result[1] = Utils.intToByte(a%b);
        return result;
    }

}
